package com.witmore.neutron.ai.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jk.common.response.ResponseResult;
import com.witmore.neutron.ai.db.entity.UserKeyDO;
import com.witmore.neutron.ai.db.mapper.UserKeyMapper;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyCreateParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyCreateResponse;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyListResponse;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyQueryParam;
import com.witmore.neutron.ai.web.apiv2.controller.vo.UserKeyUpdateParam;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.service.UserKeyService;
import com.witmore.neutron.ai.web.utils.RandomCodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户API密钥服务实现类
 * Author: 豆子高
 * Date: 2025/09/04
 */
@Slf4j
@Service
public class UserKeyServiceImpl implements UserKeyService {

    @Autowired
    private UserKeyMapper userKeyMapper;

    @Override
    public ResponseResult<UserKeyCreateResponse> createUserKey(UserKeyCreateParam createParam) {
        try {
            // 获取当前用户信息
            Integer currentUserId = GlobalAccountSession.getUserInfo().getId();
            Long currentProviderId = null;
            if (GlobalAccountSession.getUserInfo().getProviderProfile() != null) {
                currentProviderId = GlobalAccountSession.getUserInfo().getProviderProfile().getProviderId().longValue();
            }

            // 检查密钥名称是否已存在
            LambdaQueryWrapper<UserKeyDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserKeyDO::getUserId, currentUserId)
                    .eq(UserKeyDO::getKeyName, createParam.getKeyName());

            UserKeyDO existingKey = userKeyMapper.selectOne(wrapper);
            if (existingKey != null) {
                return ResponseResult.fail(400, "API密钥名称已存在");
            }

            // 生成API密钥
            String apiKey = generateApiKey();

            // 创建新的API密钥记录
            UserKeyDO userKeyDO = new UserKeyDO();
            userKeyDO.setUserId(currentUserId.longValue());
            userKeyDO.setProviderId(currentProviderId);
            userKeyDO.setKeyName(createParam.getKeyName());
            userKeyDO.setApiKey(apiKey);
            userKeyDO.setActiveStatus(1); // 默认激活
            userKeyDO.setRemark(createParam.getRemark());
            userKeyDO.setCreateTime(LocalDateTime.now());
            userKeyDO.setUpdateTime(LocalDateTime.now());

            int result = userKeyMapper.insert(userKeyDO);
            if (result > 0) {
                // 构造响应对象
                UserKeyCreateResponse response = new UserKeyCreateResponse();
                response.setId(userKeyDO.getId());
                response.setKeyName(userKeyDO.getKeyName());
                response.setApiKey(userKeyDO.getApiKey());
                response.setRemark(userKeyDO.getRemark());
                return ResponseResult.success(response);
            } else {
                return ResponseResult.fail(500, "创建API密钥失败");
            }
        } catch (Exception e) {
            log.error("创建API密钥异常", e);
            return ResponseResult.fail(500, "创建API密钥失败：" + e.getMessage());
        }
    }

    @Override
    public ResponseResult<Void> deleteUserKey(Integer id) {
        try {
            // 获取当前用户信息
            Integer currentUserId = GlobalAccountSession.getUserInfo().getId();

            // 查询密钥是否存在且属于当前用户
            UserKeyDO userKeyDO = userKeyMapper.selectById(id);
            if (userKeyDO == null) {
                return ResponseResult.fail(404, "API密钥不存在");
            }

            if (!userKeyDO.getUserId().equals(currentUserId.longValue())) {
                return ResponseResult.fail(403, "无权删除此API密钥");
            }

            int result = userKeyMapper.deleteById(id);
            if (result > 0) {
                return ResponseResult.success();
            } else {
                return ResponseResult.fail(500, "删除API密钥失败");
            }
        } catch (Exception e) {
            log.error("删除API密钥异常", e);
            return ResponseResult.fail(500, "删除API密钥失败：" + e.getMessage());
        }
    }

    @Override
    public Page<UserKeyListResponse> getUserKeyPage(UserKeyQueryParam queryParam) {
        // 获取当前用户信息
        Integer currentUserId = GlobalAccountSession.getUserInfo().getId();
        // 分页查询
        Page<UserKeyDO> doPage = userKeyMapper.selectPage(new Page<>(queryParam.getPage(), queryParam.getSize()), new LambdaQueryWrapper<UserKeyDO>()
                .eq(UserKeyDO::getUserId, currentUserId)
                .like(StringUtils.hasText(queryParam.getKeyName()), UserKeyDO::getKeyName, queryParam.getKeyName())
                .eq(queryParam.getActiveStatus() != null, UserKeyDO::getActiveStatus, queryParam.getActiveStatus())
                .orderByDesc(UserKeyDO::getActiveStatus)
                .orderByDesc(UserKeyDO::getCreateTime)
        );

        // 转换为VO并脱敏处理
        List<UserKeyListResponse> responseList = doPage.getRecords().stream().map(this::convertToListResponse).collect(Collectors.toList());

        Page<UserKeyListResponse> responsePage = new Page<>();
        responsePage.setRecords(responseList);
        responsePage.setCurrent(doPage.getCurrent());
        responsePage.setSize(doPage.getSize());
        responsePage.setTotal(doPage.getTotal());
        responsePage.setPages(doPage.getPages());

        return responsePage;
    }

    @Override
    public ResponseResult<Void> updateUserKey(UserKeyUpdateParam updateParam) {
        try {
            // 获取当前用户信息
            Integer currentUserId = GlobalAccountSession.getUserInfo().getId();

            // 查询密钥是否存在且属于当前用户
            UserKeyDO userKeyDO = userKeyMapper.selectById(updateParam.getId());
            if (userKeyDO == null) {
                return ResponseResult.fail(404, "API密钥不存在");
            }

            if (!userKeyDO.getUserId().equals(currentUserId.longValue())) {
                return ResponseResult.fail(403, "无权编辑此API密钥");
            }

            // 如果更新了密钥名称，需要检查新名称是否已存在
            if (StringUtils.hasText(updateParam.getKeyName()) && !updateParam.getKeyName().equals(userKeyDO.getKeyName())) {
                LambdaQueryWrapper<UserKeyDO> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(UserKeyDO::getUserId, currentUserId)
                        .eq(UserKeyDO::getKeyName, updateParam.getKeyName())
                        .ne(UserKeyDO::getId, updateParam.getId()); // 排除当前记录

                UserKeyDO existingKey = userKeyMapper.selectOne(wrapper);
                if (existingKey != null) {
                    return ResponseResult.fail(400, "API密钥名称已存在");
                }
            }

            // 更新密钥信息
            UserKeyDO updateEntity = new UserKeyDO();
            updateEntity.setId(updateParam.getId());
            if (StringUtils.hasText(updateParam.getKeyName())) {
                updateEntity.setKeyName(updateParam.getKeyName());
            }
            updateEntity.setRemark(updateParam.getRemark()); // 允许设置为空
            updateEntity.setUpdateTime(LocalDateTime.now());

            int result = userKeyMapper.updateById(updateEntity);
            if (result > 0) {
                return ResponseResult.success();
            } else {
                return ResponseResult.fail(500, "更新API密钥失败");
            }
        } catch (Exception e) {
            log.error("更新API密钥异常", e);
            return ResponseResult.fail(500, "更新API密钥失败：" + e.getMessage());
        }
    }

    /**
     * 生成API密钥
     *
     * @return API密钥字符串
     */
    private String generateApiKey() {
        return "uni-" + RandomCodeGenerator.generateRandomCode(32);
    }

    /**
     * 转换DO为列表响应VO
     *
     * @param userKeyDO 用户密钥DO
     * @return 列表响应VO
     */
    private UserKeyListResponse convertToListResponse(UserKeyDO userKeyDO) {
        UserKeyListResponse response = new UserKeyListResponse();
        response.setId(userKeyDO.getId());
        response.setProviderId(userKeyDO.getProviderId());
        response.setUserId(userKeyDO.getUserId());
        response.setKeyName(userKeyDO.getKeyName());
        response.setApiKey(maskApiKey(userKeyDO.getApiKey())); // 脱敏处理
        response.setActiveStatus(userKeyDO.getActiveStatus());
        response.setUpdateTime(userKeyDO.getUpdateTime());
        response.setCreateTime(userKeyDO.getCreateTime());
        response.setRemark(userKeyDO.getRemark());
        response.setLastUsedTime(userKeyDO.getLastUsedTime());
        return response;
    }

    /**
     * API密钥脱敏处理
     *
     * @param apiKey 原始API密钥
     * @return 脱敏后的API密钥
     */
    private String maskApiKey(String apiKey) {
        if (StringUtils.hasText(apiKey) && apiKey.length() > 8) {
            // 显示前4位和后4位，中间用星号代替
            String prefix = apiKey.substring(0, 4);
            String suffix = apiKey.substring(apiKey.length() - 4);
            int maskLength = apiKey.length() - 8; // 总长度减去前后各4位
            String mask = "*".repeat(maskLength);
            return prefix + mask + suffix;
        }
        return apiKey;
    }
}
